/*
 * Copyright (c) 2009, Russell Weir
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "hxvm.h"


DEFINE_KIND( k_pointer );


/**
* Clears the last error
*/
static void clearError(VM_Descriptor *vd) {
	if(!vd) return;
	if(vd->last_error)
		free(vd->last_error);
	vd->last_error = NULL;
}

/**
* Sets the current error on the VM_Descriptor, freeing any previous
* error message on it.
*
* @param vd VM_Descriptor pointer
* @param err Null terminated error string. NULL pointer will just clear
**/
static void setError(VM_Descriptor *vd, const char *err) {
	if(!vd) return;
	clearError(vd);
	if(!err)
		vd->last_error = strdup("Missing error.");
	else
		vd->last_error = strdup(err);
#ifdef DEBUG
	fprintf(stderr, "Error: %s\n", vd->last_error);
#endif
}

static void hxvm_destroy_pointer( value pointer )
{
	if( val_is_kind(pointer, k_pointer) ) {
		val_gc( pointer, NULL );
		VM_Pointer *p = POINTER( pointer );
		if(!p)
			return;
		switch( p->type ) {
		case PTR_DATA:
			if(p->data)
				free(p->data);
			break;
		case PTR_FUNCTION:
			break;
		}
		free(p);
	}
}

